<?php
declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\model\Plugin;
use think\facade\Db;
use think\facade\View;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(\think\Request $request, \Closure $next)
    {
        /*判断登陆状态*/
        if ($this->login_check() && !preg_match('/login/', $request->pathinfo())) {
            return redirect('/admin/login/index?url='.$request->rootUrl().'/'.$request->pathinfo());
        }

        /*判断插件是否启用*/
        if($request->rootUrl() == '/plugin'){
            $res = $this->plugin_check($request);
            if($res){
                return redirect('/admin/error?msg='.$res);
            }
        }

        return $next($request);
    }

    /**
     * 插件逻辑
     * @param $request
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function plugin_check($request){
        $plugin_name = strtolower(explode('/',$request->pathinfo())[0]);
        $plugin = Plugin::where('name',$plugin_name)->find();
        if($plugin){
            View::assign('plugin',$plugin);
            if($plugin->frozen == '关闭'){
                return '插件已关闭';
            }
        }else{
            return '插件异常';
        }
        return false;
    }

    /**
     * 登陆逻辑
     * @return bool
     */
    protected function login_check(): bool
    {
        try {
            $user = auth();
            if ($user) {
                View::assign('user', $user);
                return $user['frozen'] == 1;
            } else {
                return true;
            }
        } catch (\Exception $e) {
            return true;
        }
    }
}
